package com.demo.example;

import org.springframework.stereotype.Controller;

import java.util.concurrent.locks.ReentrantLock;

@Controller
public class StudentLockController {
    private static int number=5;
    private ReentrantLock rl=new ReentrantLock();
    public boolean get(){
        String name = Thread.currentThread().getName();
        while (!rl.tryLock()){
            try {
                //获取锁等待时间
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        };
        try {
            if(number>0){
                //模拟业务处理时间
                Thread.sleep(1000);
                System.out.println(name+"业务处理成功");
                number--;
                return true;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(rl.isLocked()){
                rl.unlock();
            }
        }
        System.out.println(name+"业务处理失败");
        return false;
    }
    public int size(){
        return number;
    }
}
